from django.shortcuts import render

from rest_framework import viewsets
from rest_framework import mixins
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
# from rest_framework.authentication import BaseAuthentication, SessionAuthentication, TokenAuthentication

from .models import Problem, Answer, Tag, Comment
from .serializers import ProblemDetailSerializer, ProblemSerializer, AnswerDetailSerializer, AnswerSerializer, \
    TagSerializer, CommentSerializer
from .filters import AnswerFilter, CommentFilter
from utils.permissions import IsOwnerOrReadOnly
from .permissions import CommentToAnswerUser


class CustomPagination(PageNumberPagination):
    page_query_param = 'p'
    page_size = 2
    max_page_size = 100
    page_size_query_param = 'page'


class ProblemListViewSet(viewsets.ModelViewSet):
    queryset = Problem.objects.all()

    # serializer_class = ProblemDetailSerializer

    def get_serializer_class(self):
        if self.action == 'list' or self.action == 'retrieve' or self.action == 'destroy':
            return ProblemDetailSerializer
        if self.action == 'create' or self.action == 'update':
            return ProblemSerializer
        return ProblemDetailSerializer

    def get_permissions(self):
        if self.action == 'create' or self.action == 'update' or self.action == 'destroy':
            return [IsOwnerOrReadOnly()]

        return []


class AnswerViewSet(viewsets.ModelViewSet):
    """
    完成对问题分页，过滤，搜索，排序的功能
    """
    queryset = Answer.objects.all()
    serializer_class = AnswerDetailSerializer
    pagination_class = CustomPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    # authentication_classes = (TokenAuthentication,SessionAuthentication)
    filter_class = AnswerFilter
    search_fields = ('content',)
    ordering_fields = ('agree_count', 'opposite_count', 'fav_count', 'share_count')
    lookup_field = 'answer_hash'

    def get_serializer_class(self):
        if self.action == 'list':
            return AnswerDetailSerializer
        elif self.action == 'create' or self.action == 'update':
            return AnswerSerializer

        return AnswerDetailSerializer

    def perform_create(self, serializer):
        instance = serializer.save()
        problem = instance.problem
        problem.answer_count += 1
        problem.save()

    def perform_destroy(self, instance):
        problem = instance.problem
        problem.answer_count -= 1
        problem.save()
        instance.delete()


class TagViewSet(mixins.RetrieveModelMixin,
                 mixins.CreateModelMixin,
                 viewsets.GenericViewSet):
    pagination_class = CustomPagination
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    # 查看和创建标签是需要用户认证
    # permission_classes = (IsOwnerOrReadOnly,)
    lookup_field = 'name'


class CommentViewSet(mixins.ListModelMixin,
                     mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin,
                     mixins.DestroyModelMixin,
                     viewsets.GenericViewSet):
    """
    list:
        获取评论
    create:
        增加评论
    retrieve:
        获取评论详情
    destroy:
        删除评论
    """
    serializer_class = CommentSerializer
    pagination_class = CustomPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = CommentFilter
    search_fields = ['@comment']
    ordering_fields = ['add_time']
    queryset = Comment.objects.all()
    lookup_field = 'id'

    def get_permissions(self):
        if self.action == 'destroy':
            return [CommentToAnswerUser()]

        return []
